package com.atguigu.auth.service.Impl;

import com.atguigu.auth.mapper.OaProcessTemplateMapper;
import com.atguigu.auth.service.OaProcessService;
import com.atguigu.auth.service.OaProcessTemplateService;
import com.atguigu.auth.service.OaProcessTypeService;
import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.process.ProcessType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 12646
 * @description 针对表【oa_process_template(审批模板)】的数据库操作Service实现
 * @createDate 2023-11-21 10:19:27
 */
@Service
public class OaProcessTemplateServiceImpl extends ServiceImpl<OaProcessTemplateMapper, ProcessTemplate>
    implements OaProcessTemplateService {
  
  @Autowired
  private OaProcessTemplateMapper processTemplateMapper;
  @Autowired
  private OaProcessTemplateService processTemplateService;
  @Autowired
  private OaProcessTypeService processTypeService;
  @Autowired
  private OaProcessService processService;
  
  @Override
  public IPage<ProcessTemplate> selectPage(Page<ProcessTemplate> pageParam) {
    // 1. 调用mapper方法实现分页查询
    Page<ProcessTemplate> processTemplatePage = baseMapper.selectPage(pageParam, null);
    // 2. 查询返回的分页数据，从数据中获取list集合
    // getRecords()方法将分页数据转换为List集合
    List<ProcessTemplate> records = processTemplatePage.getRecords();
    // 3. 遍历list集合，得到每个对象审批类型ID
    for (ProcessTemplate record : records) {
      Long processTypeId = record.getProcessTypeId();
      // 4. 根据审批模版表中的审批类型ID，查询获取对应名称
      LambdaQueryWrapper<ProcessType> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(ProcessType::getId, processTypeId);
      ProcessType processType = processTypeService.getOne(wrapper);
      if (processType == null) {
        continue;
      }
      // 5. 完成封装processTypeName
      record.setProcessTypeName(processType.getName());
    }
    return processTemplatePage;
  }
  
  @Override
  public void publish(Long id) {
    // 1. 根据id查询模版信息
    ProcessTemplate processTemplate = processTemplateService.getById(id);
    processTemplate.setStatus(1);
    processTemplateMapper.updateById(processTemplate);
    // TODO 部署流程定义，后续完善
    // 优先发布在线流程设计
    if (!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())) {
      processService.deployByZip(processTemplate.getProcessDefinitionPath());
    }
  }
}




